package main

import (
	"embed"
	"html/template"
	"io"
	"io/fs"
	"net/http"
	"os"
	"time"

	"gitee.com/sillyman/mixlog"
	"github.com/go-playground/validator/v10"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/labstack/gommon/log"
)

//go:embed views
var embededViewFiles embed.FS

// 自定义表单验证器
type customValidator struct{ validator *validator.Validate }

func (cv *customValidator) Validate(i interface{}) error { return cv.validator.Struct(i) }

// 自定义的模版引擎struct
type customTemplate struct {
	templates *template.Template
}

func (t *customTemplate) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	return t.templates.ExecuteTemplate(w, name, data)
}

// mustSetEcho 初始化 echo 引擎
func mustSetEcho(e *echo.Echo, debug bool) {
	mixlog.Debug("已加载资源文件")

	e.Use(middleware.Logger())
	if l, ok := e.Logger.(*log.Logger); ok {
		if debug {
			l.SetLevel(log.INFO)

		} else {
			l.SetLevel(log.WARN)
		}

		l.SetHeader("${time_rfc3339} ${level} ${short_file}($line)")
		l.SetOutput(os.Stdout)
	}

	// 绑定自定义表单验证器
	e.Validator = &customValidator{validator: validator.New()}

	// 静态文件目录
	// e.Static("/assets", "./views/assets")

	fsys, err := fs.Sub(embededViewFiles, "views")
	if err != nil {
		mixlog.Fatalf("打开嵌入的静态文件失败: %s", err)
	}
	e.GET("/assets/*", echo.WrapHandler(http.FileServer(http.FS(fsys))))
	mixlog.Debug("已设置HTTP静态文件服务")

	// 注册 HTML 模板文件
	// e.Renderer = &customTemplate{templates: template.Must(
	// 	template.ParseFiles(
	// 		"./views/index.html",
	// 	),
	// )}

	indexBytes, err := embededViewFiles.ReadFile("views/index.html")
	if err != nil {
		mixlog.Fatalf("打开views/index.html失败: %s", err)
	}
	e.Renderer = &customTemplate{templates: template.Must(
		template.New("index.html").Parse(string(indexBytes)),
	)}
	mixlog.Debug("已加载HTML模板文件")

	// 其它设置
	e.Debug = debug
	if !e.Debug {
		e.Use(middleware.Recover())
	}
	e.HideBanner = true
	e.DisableHTTP2 = true
	e.Server.ReadTimeout = 15 * time.Second
	e.Server.WriteTimeout = 15 * time.Second
}
